import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray, DragDropModule} from '@angular/cdk/drag-drop';

import { SidebarComponent } from './components/sidebar/sidebar.component';
import { SingleColumnContainerComponent } from './components/layout-containers/single-column.component';
import { TwoColumnsContainerComponent } from './components/layout-containers/two-columns.component';
import { ThreeColumnsContainerComponent } from './components/layout-containers/three-columns.component';
import { FourColumnsContainerComponent } from './components/layout-containers/four-columns.component';
import { TabContainerComponent } from './components/layout-containers/tab-container.component';
import { StepContainerComponent } from './components/layout-containers/step-container.component';
import { DroppableDirective } from './directives/droppable.directive';
import { LayoutContainer, DraggableItem, ContainerType } from './models/layout.models';
import { DragDropService } from './services/drag-drop.service';

@Component({
  selector: 'app-root',
  template: `
    <div class="app-container">
      <app-sidebar></app-sidebar>

      <div class="main-content">
        <div class="toolbar">
          <div class="toolbar-title">页面设计器</div>
          <div class="toolbar-actions">
            <button class="btn btn-outline" (click)="onSave()">
              <i class="material-icons">save</i>
              保存
            </button>
            <button class="btn btn-outline" (click)="onPreview()">
              <i class="material-icons">visibility</i>
              预览
            </button>
            <button class="btn btn-primary" (click)="onPublish()">
              <i class="material-icons">publish</i>
              发布
            </button>
            <button class="btn btn-outline" (click)="onClear()">
              <i class="material-icons">clear</i>
              清空
            </button>
          </div>
        </div>

        <div class="canvas-container">
          <div
            class="canvas"
            cdkDropList
            [cdkDropListData]="containers"
            (cdkDropListDropped)="onCanvasDrop($event)"
            [appDroppable]="this"
            (itemDropped)="onNativeDrop($event)">

            <div *ngIf="containers.length === 0" class="empty-canvas">
              <i class="material-icons">inbox</i>
              <p>拖拽组件到此处开始设计</p>
              <span>从左侧组件库中选择布局容器或组件拖拽到此处</span>
            </div>

            <!-- 可拖拽排序的容器列表 -->
            <div
              cdkDropList
              id="canvas-containers"
              [cdkDropListData]="containers"
              (cdkDropListDropped)="onContainerReorder($event)"
              class="containers-list">

              <div
                *ngFor="let container of containers; let i = index"
                cdkDrag
                [cdkDragData]="getContainerDragData(container)"
                class="container-drag-item">

                <div class="drag-handle" cdkDragHandle>
                  <i class="material-icons">drag_handle</i>
                </div>

                <ng-container [ngSwitch]="container.type">
                  <app-single-column-container
                    *ngSwitchCase="'single-column'"
                    [id]="container.id"
                    [containerData]="container"
                    (delete)="onContainerDelete($event)">
                  </app-single-column-container>

                  <app-two-columns-container
                    *ngSwitchCase="'two-columns'"
                    [id]="container.id"
                    [containerData]="container"
                    (delete)="onContainerDelete($event)">
                  </app-two-columns-container>

                  <app-three-columns-container
                    *ngSwitchCase="'three-columns'"
                    [id]="container.id"
                    [containerData]="container"
                    (delete)="onContainerDelete($event)">
                  </app-three-columns-container>

                  <app-four-columns-container
                    *ngSwitchCase="'four-columns'"
                    [id]="container.id"
                    [containerData]="container"
                    (delete)="onContainerDelete($event)">
                  </app-four-columns-container>

                  <app-tab-container
                    *ngSwitchCase="'tab-container'"
                    [id]="container.id"
                    [containerData]="container"
                    (delete)="onContainerDelete($event)">
                  </app-tab-container>

                  <app-step-container
                    *ngSwitchCase="'step-container'"
                    [id]="container.id"
                    [containerData]="container"
                    (delete)="onContainerDelete($event)">
                  </app-step-container>
                </ng-container>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styleUrls: ['./app.component.scss'],
  standalone: true,
  imports: [
    CommonModule,
    SidebarComponent,
    SingleColumnContainerComponent,
    TwoColumnsContainerComponent,
    ThreeColumnsContainerComponent,
    FourColumnsContainerComponent,
    TabContainerComponent,
    StepContainerComponent,
    DroppableDirective,
    DragDropModule
  ],
})
export class AppComponent {
  containers: LayoutContainer[] = [];

  constructor(private dragDropService: DragDropService) {}

  // CDK拖拽排序事件
  onContainerReorder(event: CdkDragDrop<LayoutContainer[]>) {
    if (event.previousContainer === event.container) {
      // 在同一列表中重新排序
      const movedContainer = this.containers[event.previousIndex];
      moveItemInArray(this.containers, event.previousIndex, event.currentIndex);

      // 更新排序字段
      this.containers.forEach((container, index) => {
        container.order = index;
      });

      console.log('容器重新排序:', movedContainer.title, '从位置', event.previousIndex, '移动到', event.currentIndex);
    }

    // 从侧边栏拖拽到画布
    const dragData = event.item.data;
    if (dragData && dragData.type === 'container') {
      this.addContainerFromDrag(dragData);
    }

  }

  // CDK画布放置事件
  onCanvasDrop(event: CdkDragDrop<any>) {
    if (event.previousContainer === event.container) {
      return; // 同一容器内排序已在onContainerReorder中处理
    }

    // 从侧边栏拖拽到画布
    const dragData = event.item.data;
    if (dragData && dragData.type === 'container') {
      this.addContainerFromDrag(dragData);
    }
  }

  // 原生拖拽事件（备用）
  onNativeDrop(event: { item: DraggableItem, target: any }) {
    if (event.item.type === 'container' && event.item.layoutType) {
      this.addContainer({
        id: event.item.id,
        type: event.item.layoutType,
        title: this.getContainerTitle(event.item.layoutType),
        children: [],
        order: this.containers.length
      });
    }
  }

  addContainerFromDrag(dragData: any) {
    const container: LayoutContainer = {
      id: this.dragDropService.generateId('container'),
      type: dragData.containerType as ContainerType,
      title: this.getContainerTitle(dragData.containerType),
      children: [],
      order: this.containers.length
    };

    this.containers.push(container);
    console.log('添加新容器:', container.title);
  }

  addContainer(container: LayoutContainer) {
    this.containers.push(container);
  }

  onContainerDelete(containerId: string) {
    this.containers = this.containers.filter(c => c.id !== containerId);
    // 重新排序
    this.containers.forEach((container, index) => {
      container.order = index;
    });
  }

  getContainerDragData(container: LayoutContainer) {
    return {
      type: 'container',
      id: container.id,
      containerType: container.type
    };
  }

  // 工具栏操作
  onSave() {
    console.log('保存布局:', this.containers);
    // 这里可以添加保存到后端的逻辑
  }

  onPreview() {
    console.log('预览布局');
    // 这里可以添加预览逻辑
  }

  onPublish() {
    console.log('发布布局');
    // 这里可以添加发布逻辑
  }

  onClear() {
    if (confirm('确定要清空所有容器吗？')) {
      this.containers = [];
    }
  }

  private getContainerTitle(type: string): string {
    const titles: Record<string, string> = {
      'single-column': '单列布局',
      'two-columns': '双列布局',
      'three-columns': '三列布局',
      'four-columns': '四列布局',
      'tab-container': 'Tab页容器',
      'step-container': 'Step页容器'
    };
    return titles[type] || '未知容器';
  }
}
